package com.kiln.juxingqs

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Process
import android.provider.Settings
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.ViewDataBinding
import client.global.commlib.ContextProvider
import client.global.commlib.base.BaseActivity
import client.global.commlib.utils.SharedUtil
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.kiln.juxingqs.aop.Log
import com.kiln.juxingqs.aop.Permissions
import com.kiln.juxingqs.dialog.MsgTitleDialog
import com.kiln.juxingqs.dialog.UpDateDialog
import com.kiln.juxingqs.ui.LoginActivity
import com.kiln.juxingqs.ui.MainActivity
import com.kiln.juxingqs.ui.TestActivity
import com.kiln.juxingqs.ui.vm.LauncherViewModel
import com.kiln.juxingqs.utils.PermissionInterceptor
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions

class LauncherActivity : BaseActivity<LauncherViewModel, ViewDataBinding>() {

    fun handle() {
        if (!SharedUtil.read("token", "").isNullOrEmpty()) {
            val intent =
                Intent(this@LauncherActivity, MainActivity::class.java)
            startActivity(intent)
        } else {
            val intent =
                Intent(this@LauncherActivity, LoginActivity::class.java)
            startActivity(intent)
        }
        finish()
    }

    override fun initData() {
        runHasPermis()
    }

    fun runHasPermis() {
//        if (BuildConfig.DEBUG) {
//            handle()
//        } else
            viewModel.getVersion()

        AppCompatDelegate.setDefaultNightMode(if(SharedUtil.read("isNight",true)) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO)

    }

    override fun observerUI() {
        viewModel.versionRet.observe(this, {
            it?.apply {
                if (it.isSuccess) {
                    data?.let {
                        if (it.state == 1) {//有新版本
                            ContextProvider.get().activity?.apply {
                                UpDateDialog(
                                    this,
                                    viewModel,
                                    it.url,
                                    it.content,
                                    it.version_name
                                ).apply {
                                    errorFun = {
                                        toast("下载失败，请重新下载")
                                        show()
                                    }
                                }.show()
                            }
                        } else if (it.state == 2) {
                            toast("系统维护")
                            Process.killProcess(0)
                        } else {
                            handle()
                        }
                    }
                } else {

                    MsgTitleDialog(this@LauncherActivity).apply {
                        title = "获取版本失败，请重新获取"
                        okTxt = "重新获取"
                        cancleTxt = "退出"
                        cancle = {
                            finish()
                        }
                        setCancelable(false)
                        setCanceledOnTouchOutside(false)
                        ok = {
                            viewModel.getVersion()
                        }
                    }.show()
                }
            }
        })
    }

    fun requestExternalStorage() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        ) {//有權限
            runHasPermis()
        } else {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                0x99
            )
        }
    }

    fun showReDialog() {
        MsgTitleDialog(this).apply {
            title = "需要开启权限"
            okTxt = "去开启"
            cancleTxt = "退出"
            cancle = {
                finish()
            }
            setCancelable(false)
            setCanceledOnTouchOutside(false)
            ok = {
                val intent: Intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                val uri = Uri.fromParts("package", packageName, null)
                intent.data = uri
                startActivityForResult(intent, 0x55)
            }

        }.show()

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        ) {//有權限
            runHasPermis()
        } else {
            showReDialog()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        ) {//有權限
            runHasPermis()
        } else {
            showReDialog()
        }
    }

    override fun getLayout(): Int {
        return R.layout.activity_launcher
    }

    override fun initViewModel(): LauncherViewModel = createViewModel()

    fun toast(text: CharSequence?) {
        ToastUtils.show(text)
    }

}